<?php
// .-----------------------------------------------------------------------------------
// | WE TRY THE BEST WAY 杭州博也网络科技有限公司
// |-----------------------------------------------------------------------------------
// | Author: 贝贝 <hebiduhebi@163.com>
// | Copyright (c) 2013-2016, http://www.itboye.com. All Rights Reserved.
// |-----------------------------------------------------------------------------------

namespace app\shop\api;
use app\common\api\BaseApi;
use app\shop\model\Product;
use app\shop\api\ProductApi;
use app\shop\api\ShoppingCartApi;
use app\shop\model\ProductSku;
use app\extend\Page;

class ProductSkuApi extends BaseApi{

    const SET_DEC   ="shop/ProductSkuApi/setDec";
    //减少库存
    const STOCK_DEC = "shop/ProductSkuApi/stockDec";
    //增加库存
    const SET_INC   ="shop/ProductSkuApi/setInc";

    /**
     * 判断是否多规格
     */
    const HAS_SKU = "shop/ProductSkuApi/hasSku";

    /*
     * 获取多规格id
     * */
    const GET_SKU_ID = "shop/ProductSkuApi/getSkuId";

    /**
     * 获取多规格名称
     */
    const GET_SKU_NAME = "shop/ProductSkuApi/getSkuName";
    const GET_INFO_BY_USER = "shop/ProductSkuApi/getInfoByUser";

    /**
     * 判断是否添加了规格信息
     */
    const IS_SKU = "shop/ProductSkuApi/isSku";

    /**
     * 查询，不分页
     */
    const QUERY_NO_PAGING = "shop/ProductSkuApi/queryNoPaging";
    /**
     * 添加
     */
    const ADD = "shop/ProductSkuApi/add";
    /**
     * 保存
     */
    const SAVE = "shop/ProductSkuApi/save";
    /**
     * 保存根据ID主键
     */
    const SAVE_BY_ID = "shop/ProductSkuApi/saveByID";

    /**
     * 删除
     */
    const DELETE = "shop/ProductSkuApi/delete";

    /**
     * 查询
     */
    const QUERY = "shop/ProductSkuApi/query";
    const CHECK_SKUID = "shop/ProductSkuApi/checkSkuID";
    /**
     * 查询一条数据
     */
    const GET_INFO = "shop/ProductSkuApi/getInfo";
    /**
     * 保存sku数据
     */
    const ADD_SKU_LIST = "shop/ProductSkuApi/addSkuList";

    /**
     * 商品联表查询
     */
    const QUERY_WITH_PRODUCT = "shop/ProductSkuApi/queryWithProduct";

    const GET_INFO_BY_SKUID = "shop/ProductSkuApi/getInfoBySkuID";
    const GET_TAX           = "shop/ProductSkuApi/getTax";
    const GET_MIN_PRICE     = "shop/ProductSkuApi/getMinPriceByPid";

    protected function _init(){
		$this->model = new ProductSku();
	}

    public function getMinPriceByPid($pid){
        //查询商品规格最低价
        $r = $this->model->where(['product_id'=>$pid])->select();
        if(false === $r) return $this->apiReturnErr($this->model->getDbError());
        if(empty($r)){
            return $this->apiReturnErr('请先设置该商品规格!');
        }
        $min_price = 1e18;
        foreach ($r as $v) {
            $min_price = min($v['price'],$min_price);
            $min_price = min($v['ori_price'],$min_price);
        }
        //查询商品最低会员价
        $r = apiCall(ProductMemberPriceApi::QUERY_NO_PAGING,[['p_id'=>$pid]]);
        if(false === $r['status']) return $this->apiReturnErr($r['info']);
        if(empty($r['info'])){
            return $this->apiReturnErr('请先设置该商品会员价!');
        }
        foreach ($r['info'] as $v) {
            $min_price = min($v['price'],$min_price);
        }
        return $this->apiReturnSuc($min_price);
    }
    public function getTax($pid,$skuid){
        $r = $this->model->join('(select sku_id as vip1_sku,price as vip1_price from itboye_product_member_price where p_id='.$pid.' and sku_id='.$skuid.' and member_group_id=1) mp on mp.vip1_sku = id','left')
        ->where(['id'=>$skuid,'product_id'=>$pid])
        ->field('price,taxation,vip1_price')->find();
        if(false === $r) return $this->apiReturnErr($this->model->getDbError());
        if(empty($r)){
            $tax = 0;
        }else{
            $tax = floatval(floatval($r['vip1_price']>0) ? $r['vip1_price']:$r['price'])*floatval($r['taxation']);
        }
        return $this->apiReturnSuc($tax);
    }

    public function getInfoBySkuID($pid=0,$sku_id=0){
        $sku_id = intval($sku_id);
        if($sku_id){
            $r = $this->getInfo(['id'=>$sku_id,'product_id'=>$pid],false,'price,ori_price,sku_desc,icon_url');
            if(!$r['status']) return $this->apiReturnErr($r['info']);
            return $this->apiReturnSuc($r['info']);
        }else{
            $r = $this->model->query(' select min(price) as price,max(ori_price) as ori_price,sku_desc,icon_url from itboye_product_sku where product_id='.$pid.' limit 1');
            if(false === $r) return $this->apiReturnErr($this->model->getDbError());
            return $this->apiReturnSuc($r[0]);
        }
    }

    public function getInfoByUser($uid,$skuid){
        $res = apiCall(ProductSkuApi::GET_INFO,[['id' => $skuid]]);
        if(!$res['status'])     return $this->apiReturnErr($res['info']);
        if(empty($res['info'])) return $this->apiReturnErr('规格失效');
        //查询会员价 >0
        $r = apiCall(ProductMemberPriceApi::GET_INFO_BY_SKUID,[$uid,$skuid,'price']);
        if(!$r['status'])     return $this->apiReturnErr($r['info']);
        if(!empty($r['info']) && floatval($r['info']['price'])>0) $res['info']['price'] = $r['info']['price'];
        // unset($r);
        return $this->apiReturnSuc($res['info']);
    }
    //根据uid和规格ID检查库存和限购 - 可带分组检验
    //-$flus 是否相加同规格，否则替换
    public function checkSkuID($uid,$skuid,$count,$flus=false,$gid=0){
        $gid = intval($gid);
        $count = intval($count);
        $map = ['id' => $skuid];
        $result   = apiCall(ProductSkuApi::GET_INFO,[$map]);
        if(!$result['status'])     return $this->apiReturnErr($result['info']);
        if(empty($result['info'])) return $this->apiReturnErr('规格失效');
        $quantity = $result['info']['quantity'];//库存
        $pid      = $result['info']['product_id'];//pid
        //比较库存
        if($quantity < $count) return $this -> apiReturnErr('库存不足');
        //查询分组信息
        if($gid){
            $r = apiCall(ProductGroupApi::GET_INFO,[['p_id'=>$pid,'g_id'=>$gid,'sku_id'=>$skuid]]);
            if(!$r['status']) return $this->apiReturnErr($r['info']);
            if(empty($r['info'])) return $this->apiReturnErr('活动分组无此规格商品');
            $now = time();
            if($r['info']['start_time']>$now || $r['info']['end_time']<$now)
                return $this->apiReturnErr('活动分组以失效');
        }
        //查询限购
        $buy_limit = 0;
        $result = apiCall(ProductAttrApi::GET_INFO,[['pid'=>$pid]]);
        if(!$result['status']) return  $this->apiReturnErr($result['info']);
        if(!empty($result['info'])){
            $buy_limit = intval($result['info']['buy_limit']);
        }
        //-是否限购
        if($buy_limit > 0){
            //查询商品名称
            $result   = apiCall(ProductApi::GET_INFO,[['id'=>$pid]]);
            if(!$result['status'] || empty($result['info'])) return $this->apiReturnErr('商品失效：'.$pid);
            $pname = $result['info']['name'];
            $r = intval(apiCall(OrdersApi::COUNT_BUY,[$uid,$pid]));
            //同商品购买数
            $this_count = 0;//此规格购物车已有数量
            $shop_count = 0;//同商品购物车已有数量
            $res = apiCall(ShoppingCartApi::QUERY_NO_PAGING,[['uid'=>$uid,'p_id'=>$pid],false,'id,psku_id,count']);
            if(!$res['status'])  return  $this->apiReturnErr($res['info']);
            if(!empty($res['info'])){
                foreach ($res['info'] as $v) {
                    if(intval($v['psku_id']) == $skuid) $this_count += intval($v['count']);
                    $shop_count = $shop_count + intval($v['count']);
                }
            }
            // trace('==count-buy==');
            // return $this -> apiReturnErr($r.':'.$count.':'.(intval($r)+$count).'?'.$buy_limit);
            if($r>=$buy_limit){
                return  $this -> apiReturnErr($pname.'限购'.$buy_limit.'件,您已全部购买');
            }
            if($r>0){
                $str = ',您已购买'.$r.'件，购物车内不得超过'.($buy_limit-$r).'件';
            }else{
                $str = '';
            };
            // return  $this -> apiReturnErr($r.'+'.$shop_count.'-'.$ori_count.'+'.$new_count);
            if($flus){
                //增减同规格件数
                if($this_count+$count<0) return $this -> apiReturnErr($pname.'购物车中过少');
                $cc = $r+$shop_count+$count;
            }else{
                //替换同规格件数
                $cc = $r+$shop_count+$count-$this_count;
            }
            if($cc>$buy_limit){
               return  $this->apiReturnErr($pname.'限购'.$buy_limit.'件'.$str);
            }
            //TODO 已售后数
        }
        return $this -> apiReturnSuc('pass');
    }
    //库存减少
    public function stockDec($pid, $pskuid, $cnt = 1){
        $map = ['id'=>$pskuid,'product_id'=>$pis];
        $result = $this->model->where($map);
        if(false === $result){
            return $this -> apiReturnErr($this -> model -> getDbError());
        }else{
            if(intval($r['quantity'])<$cnt) return $this -> apiReturnErr('库存不够');
            $result = $this->model->where($map)-> setDec('quantity', $cnt);
            if ($result === false) {
                return $this -> apiReturnErr($this -> model -> getDbError());
            } else {
                return $this -> apiReturnSuc($result);
            }
        }
    }

    public function queryWithProduct($map = null, $page = ['curpage'=>0,'size'=>10], $order = false, $params = false, $fields = false){
        $query = $this -> model -> join('itboye_product on product_id = itboye_product.id');
        if(!is_null($map)) $query = $query->where($map);
        if($order)         $query = $query->order($order);
        if($fields)        $query = $query->field($fields);
        $list = $query -> page($page['curpage'] . ',' . $page['size']) -> select();

        if (!$list) {
            $error = $this -> model -> getDbError();
            return $this -> apiReturnErr($error);
        }

        $count = $this -> model -> join('itboye_product on product_id = itboye_product.id') -> where($map) -> count();
        // 查询满足要求的总记录数
        $Page = new Page($count, $page['size']);

        //分页跳转的时候保证查询条件
        if ($params) {
            foreach ($params as $key => $val) {
                $Page -> parameter[$key] = urlencode($val);
            }
        }

        // 实例化分页类 传入总记录数和每页显示的记录数
        $show = $Page -> show();
        return $this -> apiReturnSuc(["show" => $show, "list" => $list]);
    }

    /**
     * 上架前判断是否添加了sku信息
     * @param bool|false $pid
     * @return 0,1
     */
    public function isSku($pid = false){
        if(false === $pid) return $this -> apiReturnErr("缺少商品id参数");
        $map = ['product_id' => $pid];
        $result = $this -> model -> where($map) -> count();

        if($result === false){
            $error = $this -> model -> getDbError();
            return $this -> apiReturnErr($error);
        }

        if($result == 0){
            return $this -> apiReturnSuc(0);
        }else{
            return $this -> apiReturnSuc(1);
        }
    }

    /**
     * 判断是否多规格
     * @param $pid
     */
    public function hasSku($pid = false){

        if(false === $pid) return $this -> apiReturnErr("缺少商品id参数");

        $map = ['product_id'=>$pid];
        $list = $this -> model -> where($map) ->select();

        if(false === $list){
            $error = $this -> model ->getDbError();
            return $this -> apiReturnErr($error);
        }

        if(is_null($list)) return $this -> apiReturnSuc(0);
        if(count($list) == 1 && $list[0]['sku_id'] == "") return $this -> apiReturnSuc(0);
        return $this -> apiReturnSuc(1);
    }

    /**
     * 获取商品skuId信息
     * @param $pid 商品id
     * @return json
     */
    public function getSkuId($pid = false,$field = false){

        if(false === $pid) return $this -> apiReturnErr("缺少商品id参数");
        if(false === $field) return $this -> apiReturnErr("缺少字段参数");

        $map = ['product_id'=>$pid];
        $list = $this -> model -> where($map) -> field($field) ->select();

        if(false === $list){
            $error = $this -> model -> getDbError();
            return $this -> apiReturnErr($error);
        }

// array (
//   0 => array (
//     'sku_id' => '127:560;128:562;',
//   ),
//   1 => array (
//     'sku_id' => '127:560;128:563;',
//   ),
//   2 => array (
//     'sku_id' => '127:561;128:562;',
//   ),
//   3 => array (
//     'sku_id' => '127:561;128:563;',
//   ),
// )
// trace('get field');
// trace($field); //sku_id
        $res = $this-> getSkuJson($list,$field);
        return $this -> apiReturnSuc($res);

    }

    /**
     * 获取规格名称
     * @param bool|false $pid
     * @param bool|false $field
     * @return array
     */
    public function getSkuName($pid = false,$field = false){

        if(false === $pid)   return $this -> apiReturnErr("缺少商品id参数");
        if(false === $field) return $this -> apiReturnErr("缺少字段参数");

        $map = ['product_id' => $pid];
        $list = $this -> model -> where($map) -> field($field) -> select();

        if(false === $list){
            $error = $this -> model -> getDbError();
            return $this -> apiReturnErr($error);
        }
        // dump($list);
        // dump($field);
        // exit;

        $res = $this -> getSkuJson($list,$field);
        return $this -> apiReturnSuc($res);

    }

    private function getSkuJson($list,$field){
        //进行数组整合
        $result = [];
        foreach($list as $vo){
            $tmp = explode(';',$vo[$field]);
            // trace('tmp--');
            // trace($tmp);
            array_pop($tmp);
            // trace('tmp--');
            // trace($tmp);
            foreach ($tmp as $k => $v) {
                if(empty($result[$k])){
                    $result[$k] = [];
                }
                array_push($result[$k],$v);
            }
        }
        //去重
        foreach($result as $k => $v){
            $result[$k] = array_unique($v);
        }
        // trace(' array_unique ');
        // trace($result);
// array (
//   0 =>
//   array (
//     0 => '127:560',
//     2 => '127:561',
//   ),
//   1 =>
//   array (
//     0 => '128:562',
//     1 => '128:563',
//   ),
// )

        $res =  [];
        $flag = [];
        $i = 0;
//         foreach ($result as $k => $v) {
// //array (
// //     0 => '127:560',
// //     2 => '127:561',
// //),
//             foreach($v as $kk => $vv){
//                 $tmp = explode(':',$vv);
//                 if(empty($flag[$tmp[0]])){
//                     $flag[$tmp[0]] = $i;
//                     $i++;
//                     $res[$flag[$tmp[0]]]['id'] = $tmp[0];
//                 }
//                 if(empty($res[$flag[$tmp[0]]]['vid'])){
//                     $res[$flag[$tmp[0]]]['vid'] = [];
//                 }
//                 array_push($res[$flag[$tmp[0]]]['vid'],$tmp[1]);
//             }
//         }

        foreach ($result as $k => $v) {
            foreach($v as $kk => $vv){
                $temp = explode(':',$vv);
                $flag[$temp[0]][] = $temp[1];
            }
        }
        foreach ($flag as $k => $v) {
            $res[$i]['id']=$k;
            $res[$i]['vid']=$v;
            $i++;
        }
        /*
        $res =
        array(
            [0]array(
                id => k0,
                vid => array(
                    [0] => v01,
                    [1] => v02,
                    [2] => v03
                    ...
                )
            ),
            [1]array(
                id => k1,
                vid => array(
                    [0] => v11,
                    [1] => v12,
                    [2] => v13,
                    ...
                )
            ),
            [2]array(
                id => k2,
                vid => array(
                    [0] => v21,
                    [1] => v22,
                    [2] => v23,
                    ...
                )
            ),
            ...
        )
         * */

        return json_encode($res);
    }


    /**
     * 保存sku数据
     * @param $id
     * @param $sku_info
     * @param $list
     * @return array
     */
    public function addSkuList($id,$has_sku,$list){

        //删除表内原有相关数据
        $this->model->startTrans();
        $flag = true;
        $error = "";
        $map = ['product_id'=>$id];

        $result = $this->model->where($map)->delete();
        if($result === false){
            $flag = false;
            $error = $this->model->getDbError();
        }

        //重新插入数据
        if($has_sku == 0){
            //统一规格
            $entity = [
                'product_id' => $id,
                'sku_id' => '',
                'ori_price' => $list['ori_price'],
                'price' => $list['price'],
                'quantity' => $list['quantity'],
                'product_code' => $list['product_code'],
                'icon_url' => '',
                'sku_desc' => "",
            ];

            if($this -> model -> create($entity,1)){
                $result = $this -> model -> add();
                if($result !== false){
                    $this -> model -> commit();
                    return $this -> apiReturnSuc($result);
                }
            }
            $error = $this -> model -> getDbError();
            $this -> model -> rollback();
            return $this -> apiReturnErr($error);

        }else{
            //多规格
            foreach($list as $vo){
                $entity = [
                    'product_id'=>$id,
                    'sku_id'=>$vo['sku_id'],
                    'ori_price'=>$vo['ori_price'],
                    'price'=>$vo['price'],
                    'quantity'=>$vo['quantity'],
                    'product_code'=>$vo['product_code'],
                    'icon_url'=>$vo['icon_url'],
                    'sku_desc'=>$vo['sku_desc'],
                ];

                if($this->model->create($entity,1)){
                    $result = $this->model->add();
                    if(false === $result){
                        $flag = false;
                        $error = $this->model->getError();
                    }
                }else{
                    $flag = false;
                    $error = $this->model->getError();
                }

            }

            if($flag){
                $this->model->commit();
                return $this->apiReturnSuc($result);
            }else{
                $this->model->rollback();
                return $this->apiReturnErr($error);
            }
        }
    }



    /*public function addSkuList($id,$sku_info,$list){
        $this->model->startTrans();
        $sql = "";
        $flag = true;
        $error = "";
        $map = array('product_id'=>$id);

        $result = $this->model->where($map)->delete();
        if($result === false){
            $flag = false;
            $error = $this->model->getDbError();
        }

        foreach($list as $vo){
            $entity = array(
                'product_id'=>$id,
                'sku_id'=>$vo['sku_id'],
                'ori_price'=>$vo['ori_price'],
                'price'=>$vo['price'],
                'quantity'=>$vo['quantity'],
                'product_code'=>$vo['product_code'],
                'icon_url'=>$vo['icon_url'],
                'sku_desc'=>$vo['sku_desc'],
            );

            if($this->model->create($entity,1)){
                $result = $this->model->add();
                if($result === false){
                    $flag = false;
                    $error = $this->model->getError();
                }
            }else{
                $flag = false;
                $error = $this->model->getError();
            }

        }


        if($flag){
            //更新 产品信息
            $entity = array(
                'has_sku'=>1,
                'sku_info'=>json_encode($sku_info,JSON_UNESCAPED_UNICODE),
            );
            $map = array('id'=>$id);
            $model = new ProductModel();
            $result = $model->where($map)->save($entity);
            if($result === false){
                $flag = false;
                $error = $this->model->getDbError();
            }
        }


        if($flag){
            $this->model->commit();
            return $this->apiReturnSuc($result);
        }else{
            $this->model->rollback();
            return $this->apiReturnErr($error);
        }

    }*/

}
